﻿using Bilibili.Model.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Bilibili.Common.Api
{
    public abstract class ApiProviderBase
    {
        protected void Init()
        {
            LoginKey = new ApiKeyInfo("783bbb7264451d82", "2653583c8873dea268ab9386918b1d65");
            AndroidKey = new ApiKeyInfo("1d8b6e7d45233436", "560c52ccd288fed045859ed18bffd973");
            WebVideoKey = new ApiKeyInfo("84956560bc028eb7", "94aba54af9065f71de72f5508f1cd42e");
            AndroidTVKey = new ApiKeyInfo("4409e2ce8ffd12b8", "59b43e04ad6965f34319062b478f83dd");
            AndroidVideoKey = new ApiKeyInfo("iVGUTjsxvpLeuDCf", "aHRmhWMLkdeMuILqORnYZocwMBpMEOdt");
        }
        public void Init(string accessKey, long userId)
        {
            AccessKey = accessKey;
            CurrentUserId = userId;
        }
        public const string Build4 = "421000";
        public const string Build5 = "5520400";
        public const string Build6 = "6235200";
        public const string Build7 = "7270300";
        public ApiKeyInfo LoginKey { get; protected set; }
        public ApiKeyInfo AndroidKey { get; protected set; }
        public ApiKeyInfo WebVideoKey { get; protected set; }
        public ApiKeyInfo AndroidTVKey { get; protected set; }
        public ApiKeyInfo AndroidVideoKey { get; protected set; }
        public abstract string AccessKey { get; set; }
        public string AndroidKeySign => $"appkey={AndroidKey.Appkey}&build={Build5}";
        public string GetSign(string url, ApiKeyInfo apiKeyInfo = null)
        {
            apiKeyInfo ??= AndroidKey;
            string str = url.Substring(url.IndexOf("?", 4) + 1);
            List<string> list = str.Split('&').ToList();
            list.Sort();
            StringBuilder stringBuilder = new StringBuilder();
            foreach (string val in list)
            {
                stringBuilder.Append(stringBuilder.Length > 0 ? "&" : string.Empty);
                stringBuilder.Append(val);
            }
            stringBuilder.Append(apiKeyInfo.Secret);
            return stringBuilder.ToString().ToMD5().ToLower();
        }
        public long TimeSpanSeconds => Convert.ToInt64((DateTime.Now - new DateTime(1970, 1, 1, 8, 0, 0, 0)).TotalSeconds);
        public long TimeSpanMilliseconds => Convert.ToInt64((DateTime.Now - new DateTime(1970, 1, 1, 8, 0, 0, 0)).TotalMilliseconds);
        public abstract long CurrentUserId { get; set; }
        public bool IsLogin => CurrentUserId != 0;
        protected abstract string ToMD5(string input);
    }
}